package com.example.infrastructure.api.advice;

import com.example.infrastructure.domain.organization.aggregate.Organization;
import com.example.infrastructure.domain.person.aggregate.Person;
import com.example.infrastructure.infrastructure.mapper.CycleAvoidingMappingContext;
import com.example.infrastructure.infrastructure.mapper.organization.OrganizationMapper;
import com.example.infrastructure.infrastructure.mapper.person.PersonMapper;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

/**
 * TODO
 *
 * @author lxh
 * @date 2020/11/18 上午11:29
 **/
@RestControllerAdvice
public class JsonResponseBodyAdvice implements ResponseBodyAdvice<Object> {
    private final PersonMapper personMapper;

    public JsonResponseBodyAdvice(PersonMapper personMapper) {
        this.personMapper = personMapper;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(
            Object body,
            MethodParameter returnType,
            MediaType selectedContentType,
            Class<? extends HttpMessageConverter<?>> selectedConverterType,
            ServerHttpRequest request,
            ServerHttpResponse response) {
        // 返回 Organization 或 Person
        if (body instanceof Organization) {
            return OrganizationMapper.INSTANCE.toDto((Organization) body, new CycleAvoidingMappingContext());
        } else if (body instanceof Person) {
            return personMapper.toDto((Person) body);
        }

        // 返回 List<Organization> 或 List<Person>
        Class<?> returnClazz = ResolvableType.forMethodParameter(returnType).resolve();
        if (returnClazz != null && returnClazz.isAssignableFrom(List.class)) {
            Class<?> genericClazz =
                    ResolvableType.forMethodParameter(returnType).resolveGeneric(0);
            if (genericClazz != null && genericClazz.isAssignableFrom(Organization.class)) {
                return OrganizationMapper.INSTANCE.toDtoList(
                        (List<Organization>) body, new CycleAvoidingMappingContext());
            } else if (genericClazz != null && genericClazz.isAssignableFrom(Person.class)) {
                return personMapper.toDtoList((List<Person>) body);
            }
        }

        return body;
    }
}
